<template>
    <div class="division_manage_list">
        <!-- 查询 -->
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="分账方信息" prop="keywords">
                            <el-input
                                v-model.trim="form.keywords"
                                clearable
                                placeholder="请输入商户名称/简称/统一社会信用代码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="主体类型" prop="split_account_type">
                            <el-select v-model="form.split_account_type" placeholder="全部类型" clearable>
                                <el-option
                                    v-for="item in mainType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <el-form-item label="授权状态" prop="authorized">
                            <el-select v-model="form.authorized" placeholder="全部状态" clearable>
                                <el-option
                                    v-for="item in authorizationStatus"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand">
                        <el-form-item label="创建时间" prop="created_at">
                            <el-date-picker
                                v-model="form.created_at"
                                type="daterange"
                                clearable
                                :default-time="defaultTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :disabled-date="disabledDate" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-show="defaultExpand"></el-col>
                    <el-col :span="8" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain class="btn-reset" @click="resetHandler">清空</el-button>
                        <el-button
                            v-if="defaultExpand"
                            class="icon_btn"
                            :text="true"
                            type="primary"
                            @click="handleExpand">
                            收起<el-icon><ArrowUp /></el-icon>
                        </el-button>
                        <el-button v-else class="icon_btn" :text="true" type="primary" @click="handleExpand">
                            展开<el-icon><ArrowDown /></el-icon>
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="division_manage_list_bottom" :class="{ division_manage_list_bottom_expand: !defaultExpand }">
            <!-- 按钮 -->
            <div class="btn-group">
                <SelectAccount name="添加分账方" @handle-close="handleClose"></SelectAccount>
            </div>
            <!-- 列表 -->
            <el-table
                ref="tableRef"
                :data="tableList"
                :height="tableHeight"
                row-key="id"
                :class="{ 'el-table-empty': !tableList?.length }">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="['split_type_name', 'authorized_name'].includes(prop)" #header>
                        <div class="custom-header-col" v-if="prop === 'split_type_name'">
                            <span>分账方式</span>
                            <ZwTooltip type="icon">
                                <template #content>
                                    逐笔订单分账：用户每支付一笔订单后，系统根据所设置分账接收方和分账比例自动发起分账。<br />
                                    单日汇总分账：单日订单支付金额汇总后，系统次日根据所设置分账接收方和分账比例自动发起分账。<br />
                                    API接入：根据第三方接口传入的分账接收方和分账金额发起分账。
                                </template>
                            </ZwTooltip>
                        </div>
                        <div class="custom-header-col" v-if="prop === 'authorized_name'">
                            <span>授权状态</span>
                            <ZwTooltip type="icon" content="分账方需先授权委托扣款功能才可进行分账。" />
                        </div>
                    </template>
                    <template #default="{ row }">
                        <template v-if="prop === 'name'">
                            <div class="corp-name">
                                <div class="corp-name-main">
                                    <ZwTooltip :content="row.name" :line="2" />
                                </div>
                                <div class="corp-name-sub" v-if="row.credit_no">
                                    <ZwTooltip :content="row.credit_no" />
                                </div>
                            </div>
                        </template>
                        <template v-if="prop === 'authorized_name'">
                            <span
                                class="custom-status-point"
                                :style="{ '--status-bgcolor': StatusColorOption[row.authorized] || '#FF6B00' }">
                                {{ row.authorized_name }}
                            </span>
                        </template>
                        <template v-if="prop === 'split_account_ratio'">
                            <span>
                                {{ getRadio(row) }}
                            </span>
                        </template>
                        <template v-if="prop === 'split_account_receiver_num'">
                            <span v-if="!row.split_account_receiver_num" style="margin-left: 10px">
                                {{ row.split_account_receiver_num }}
                            </span>
                            <span
                                v-else
                                @click="openAcceptorHandler(row)"
                                style="color: #ff6b00; margin-left: 10px; cursor: pointer">
                                {{ row.split_account_receiver_num }}
                            </span>
                        </template>
                        <template v-if="prop === 'operations'">
                            <span
                                v-for="{ label, fn, ref } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                class="table-button button--small"
                                >{{ label }}</span
                            >
                        </template>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="table-empty">
                        <img
                            src="https://img.static-keyid.cn/toolspace/scrm/2023/10/1697683499137ngcb4fpdwjr9ijb4.png" />
                        <div>暂无数据</div>
                    </div>
                </template>
            </el-table>
            <!-- 分页 -->
            <Pagination
                class="custom-bottom-page"
                :total="totalCount"
                :page-size="form.page_size"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
        <AcceptInfo v-model="showInfo" :tableData="acceptArr" :splitType="splitType"></AcceptInfo>
    </div>
</template>

<script setup name="divisionManageList">
import { ref, reactive, computed, onActivated, onDeactivated, h, nextTick } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, cloneDeep, isDayAfter, confirmHandler } from '@/commons/utils';
import { setLayout, resetLayout, resizeTableHeight, getTableHeight, resizeTableRemove } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import ZwTooltip from '@/components/ZwTooltip.vue';
import SelectAccount from '../components/SelectAccount/SelectAccount.vue';
import AcceptInfo from '../components/AcceptInfo.vue';

const showInfo = ref(false);

/* ----------------------------添加分账方-start---------------------------- */
const handleClose = value => {
    value && queryListHandler();
};

/* ----------------------------添加分账方-end---------------------------- */

const mainType = reactive(packSelectObjUtil(constants.MAIN_TYPE)); // 主体类型
const authorizationStatus = reactive(packSelectObjUtil(constants.AUTHORIZATION_STATUS, false)); // 授权状态

const router = useRouter(); // 路由

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]; // 默认日期

const form = reactive({
    page: 1, //页码数
    page_size: 10, //每页显示数
    keywords: '', //商户信息 商户名称/简称/统一社会代码
    split_account_type: null, //主体类型 1-企业商户 2-个人工商户 3-个人商户
    authorized: null, //授权状态 AUTHORIZED-已授权 UNAUTHORIZED-未授权 PROCESSING-授权进行中 UNBIND-解除授权
    created_at: [] //创建时间
}); // 查询表单
let formClone = cloneDeep(form); // 查询备份
const formRef = ref(null); // form ref
const tableRef = ref(null);
const totalCount = ref(0); // 数据总数
let tableList = reactive([]); // 表格数据
let defaultExpand = ref(true); // 展开/收起

// 控制查询展开收起
const handleExpand = () => {
    defaultExpand.value = !defaultExpand.value;
    setTimeout(() => {
        getTableHeight('division_manage_list_bottom', tableHeight, 'custom-bottom-page');
    });
};
// 禁止查询的日期
const disabledDate = date => {
    return isDayAfter(date);
};

// 授权状态颜色
const StatusColorOption = {
    UNAUTHORIZED: '#EAEAEA',
    AUTHORIZED: '#60B900',
    PROCESSING: '#3F87F5',
    UNBIND: '#FF6B00'
};

// 格式化比例
const getRadio = ({ split_type, split_account_ratio }) =>
    split_type === 'API' || ['--', null, undefined, ''].includes(split_account_ratio)
        ? '--'
        : split_account_ratio + '%';

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '分账方信息', prop: 'name', minWidth: '300' },
        { label: '主体类型', prop: 'split_account_type_name', minWidth: '170' },
        { label: '分账接收方数量', prop: 'split_account_receiver_num', minWidth: '170' },
        { label: '分出总比例', prop: 'split_account_ratio', minWidth: '170' },
        { label: '分账方式', prop: 'split_type_name', minWidth: '170' },
        { label: '授权状态', prop: 'authorized_name', minWidth: '170' },
        { label: '创建时间', prop: 'created_at', minWidth: '170' },
        { label: '操作', prop: 'operations', width: '110', fixed: 'right' }
    ];
    return baseTableColumns;
});

// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    formClone.page = form.page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.page_size = perPage;
    formClone.page = form.page;
    formClone.page_size = form.page_size;
    queryListHandler();
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryListHandler();
};

/**
 * 分页查询
 */
// let loading = ref(false);
const queryListHandler = async notScroll => {
    // loading.value = true;
    const _form = cloneDeep(formClone);
    const res = await request('splitAccountManageList', _form);
    // loading.value = false;
    const list = (res?.data?.data || [])?.map(item => {
        // 根据不同状态显示不同按钮
        const btns = {
            0: { label: '授权', fn: routerHandler, ref: 'authRef' },
            1: { label: '删除', fn: removeHandler, ref: 'removeRef' },
            2: { label: '设置', fn: routerHandler, ref: 'settingRef' }
        };
        item.operations = [];
        // 只有未授权才显示授权和删除按钮
        if (item.authorized == 'UNAUTHORIZED') {
            item.operations = [btns[0], btns[1]];
        } else {
            item.operations = [btns[2]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.total;
    nextTick(() => {
        // 加载数据后将table滚动条滚动到table最顶部和最左边
        !notScroll && tableRef?.value?.scrollTo(0, 0);
    });
};

/**
 * 跳转页面
 */
const routerHandler = (row, ref) => {
    const paths = {
        authRef: '/division/manage/authentication', // 授权页
        settingRef: '/division/manage/view' // 设置页
    };
    router.push({
        path: paths[ref],
        query: { id: row.id }
    });
};

/**
 * 删除
 */
const removeHandler = row => {
    // 删除接口splitAccountManageDelete
    confirmHandler({
        params: ['splitAccountManageDelete', { id: row.id }],
        title: `确定要删除分账方【${row.name}】吗？ `,
        callback: queryListHandler,
        successMsg: '删除成功'
    });
};

// 页面可见监听函数
const visibilitychange = () => {
    if (document.visibilityState === 'visible') {
        queryListHandler();
    }
};

const getAllData = () => {
    queryListHandler();
};

const acceptArr = ref([]);
let splitType = ref('');
const openAcceptorHandler = async row => {
    // 打开接收方弹窗
    const { data } = await request('splitAccountManageView', { id: row.id });
    (data?.split_account_receiver_info || []).map(x => {
        x.corp_name = x.name;
        x.corp_unified_social_credit_code = x.credit_no;
        x.corp_main_type_name = x.split_account_type_name;
    });
    splitType.value = data?.split_account_info?.split_type;
    acceptArr.value = data?.split_account_receiver_info || [];
    showInfo.value = true;
};

let tableHeight = ref(300);
onActivated(() => {
    // Object.keys(formClone || {})?.forEach(key => {
    //     form[key] = formClone[key];
    // });
    setLayout('division-manage-layout');
    getAllData();
    setTimeout(() => {
        resizeTableHeight('division_manage_list_bottom', tableHeight, 'custom-bottom-page');
    }, 0);

    // useDocumentVisibility('add', visibilitychange);
});
onDeactivated(() => {
    resetLayout('division-manage-layout');
    resizeTableRemove();
    // useDocumentVisibility('remove', visibilitychange);
});

onBeforeRouteLeave((to, from, next) => {
    next();
});
</script>
<style lang="scss">
.division-manage-layout {
    height: 100%;
    padding: 0 !important;
    background-color: #f3f3f3 !important;
}
.not-border td.el-table__cell {
    border-bottom: 0;
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
